package cn.edu.baiyunu.myapplication.ui.screens.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import cn.edu.baiyunu.myapplication.data.model.SavingsGoal
import cn.edu.baiyunu.myapplication.ui.utils.IconUtils

/**
 * 储蓄目标添加/编辑对话框 - 紧凑版
 */
@Composable
fun SavingsGoalDialog(
    goal: SavingsGoal?,
    onDismiss: () -> Unit,
    onSave: (String, Double, Double, String, String) -> Unit
) {
    // 是否是编辑模式
    val isEditMode = goal != null
    
    // 表单状态
    var name by remember { mutableStateOf(goal?.name ?: "") }
    var targetAmount by remember { mutableStateOf(goal?.targetAmount?.toString() ?: "") }
    var savingRate by remember { mutableStateOf(goal?.savingRate?.toString() ?: "") }
    var selectedIcon by remember { mutableStateOf(goal?.icon ?: "savings") }
    var selectedType by remember { mutableStateOf(goal?.type ?: "short") }
    
    // 显示图标选择器
    var showIconSelector by remember { mutableStateOf(false) }
    
    // 验证状态
    val isValid = name.isNotBlank() && 
        targetAmount.toDoubleOrNull() != null && 
        savingRate.toDoubleOrNull() != null &&
        selectedIcon.isNotBlank() &&
        selectedType.isNotBlank()
    
    // 预定义图标和类型
    val availableIcons = listOf(
        "savings", "account_balance", "credit_card", "payments", "currency_exchange",
        "home", "directions_car", "flight", "school", "family_restroom",
        "card_giftcard", "celebration", "medical_services", "spa", "sports_esports"
    )
    
    // 目标类型选项
    val goalTypes = mapOf(
        "short" to "短期",
        "medium" to "中期",
        "long" to "长期"
    )
    
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = RoundedCornerShape(20.dp),
            color = Color(0xE6222222)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        brush = Brush.verticalGradient(
                            colors = listOf(
                                Color(0xFF6A11CB).copy(alpha = 0.2f),
                                Color(0xFF2575FC).copy(alpha = 0.2f)
                            )
                        )
                    )
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                ) {
                    // 头部：标题和图标
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 标题
                        Text(
                            text = if (isEditMode) "编辑储蓄目标" else "添加储蓄目标",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color.White,
                            modifier = Modifier.weight(1f)
                        )
                        
                        // 图标选择器按钮
                        Box(
                            modifier = Modifier
                                .size(40.dp)
                                .clip(CircleShape)
                                .background(Color.White.copy(alpha = 0.1f))
                                .border(1.dp, Color.White.copy(alpha = 0.2f), CircleShape)
                                .clickable { showIconSelector = true },
                            contentAlignment = Alignment.Center
                        ) {
                            val icon = IconUtils.getIconByName(selectedIcon)
                            Icon(
                                imageVector = icon,
                                contentDescription = null,
                                tint = Color.White,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                    }
                    
                    // 名称输入
                    OutlinedTextField(
                        value = name,
                        onValueChange = { name = it },
                        label = { Text("目标名称", fontSize = 12.sp) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 8.dp),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color.White,
                            unfocusedBorderColor = Color.White.copy(alpha = 0.5f),
                            focusedLabelColor = Color.White,
                            unfocusedLabelColor = Color.White.copy(alpha = 0.7f),
                            cursorColor = Color.White,
                            focusedTextColor = Color.White,
                            unfocusedTextColor = Color.White
                        ),
                        textStyle = LocalTextStyle.current.copy(fontSize = 14.sp),
                        singleLine = true
                    )
                    
                    // 金额和储蓄率（放在同一行）
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 8.dp),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // 目标金额
                        OutlinedTextField(
                            value = targetAmount,
                            onValueChange = { 
                                if (it.isEmpty() || it.matches(Regex("^\\d*\\.?\\d*$"))) {
                                    targetAmount = it
                                }
                            },
                            label = { Text("目标金额", fontSize = 12.sp) },
                            modifier = Modifier.weight(1f),
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedBorderColor = Color.White,
                                unfocusedBorderColor = Color.White.copy(alpha = 0.5f),
                                focusedLabelColor = Color.White,
                                unfocusedLabelColor = Color.White.copy(alpha = 0.7f),
                                cursorColor = Color.White,
                                focusedTextColor = Color.White,
                                unfocusedTextColor = Color.White
                            ),
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Default.AttachMoney,
                                    contentDescription = null,
                                    tint = Color.White.copy(alpha = 0.7f),
                                    modifier = Modifier.size(16.dp)
                                )
                            },
                            textStyle = LocalTextStyle.current.copy(fontSize = 14.sp),
                            singleLine = true
                        )
                        
                        // 储蓄率
                        OutlinedTextField(
                            value = savingRate,
                            onValueChange = { 
                                if (it.isEmpty() || it.matches(Regex("^\\d*\\.?\\d*$"))) {
                                    savingRate = it
                                }
                            },
                            label = { Text("储蓄率%", fontSize = 12.sp) },
                            modifier = Modifier.weight(0.8f),
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedBorderColor = Color.White,
                                unfocusedBorderColor = Color.White.copy(alpha = 0.5f),
                                focusedLabelColor = Color.White,
                                unfocusedLabelColor = Color.White.copy(alpha = 0.7f),
                                cursorColor = Color.White,
                                focusedTextColor = Color.White,
                                unfocusedTextColor = Color.White
                            ),
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Default.Percent,
                                    contentDescription = null,
                                    tint = Color.White.copy(alpha = 0.7f),
                                    modifier = Modifier.size(16.dp)
                                )
                            },
                            textStyle = LocalTextStyle.current.copy(fontSize = 14.sp),
                            singleLine = true
                        )
                    }
                    
                    // 目标类型选择器
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = if (showIconSelector) 8.dp else 12.dp),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        goalTypes.forEach { (type, label) ->
                            SavingsGoalTypeChip(
                                label = label,
                                selected = selectedType == type,
                                onSelected = { selectedType = type },
                                modifier = Modifier.weight(1f)
                            )
                        }
                    }
                    
                    // 图标选择器 (紧凑设计)
                    if (showIconSelector) {
                        LazyVerticalGrid(
                            columns = GridCells.Fixed(5),
                            contentPadding = PaddingValues(4.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                            horizontalArrangement = Arrangement.spacedBy(8.dp),
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(100.dp)
                                .background(
                                    color = Color.Black.copy(alpha = 0.2f),
                                    shape = RoundedCornerShape(12.dp)
                                )
                                .padding(8.dp)
                        ) {
                            items(availableIcons) { iconName ->
                                IconSelectionItem(
                                    iconName = iconName,
                                    isSelected = selectedIcon == iconName,
                                    onClick = { 
                                        selectedIcon = iconName
                                        showIconSelector = false
                                    }
                                )
                            }
                        }
                    }
                    
                    // 按钮行
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        OutlinedButton(
                            onClick = onDismiss,
                            modifier = Modifier.weight(1f),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = Color.White
                            ),
                            border = ButtonDefaults.outlinedButtonBorder.copy(
                                brush = Brush.horizontalGradient(
                                    listOf(
                                        Color.White.copy(alpha = 0.3f),
                                        Color.White.copy(alpha = 0.2f)
                                    )
                                )
                            )
                        ) {
                            Text("取消", fontSize = 14.sp)
                        }
                        
                        Button(
                            onClick = {
                                if (isValid) {
                                    onSave(
                                        name,
                                        targetAmount.toDoubleOrNull() ?: 0.0,
                                        savingRate.toDoubleOrNull() ?: 0.0,
                                        selectedIcon,
                                        selectedType
                                    )
                                }
                            },
                            enabled = isValid,
                            modifier = Modifier.weight(1f),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF6A11CB),
                                disabledContainerColor = Color(0xFF6A11CB).copy(alpha = 0.5f)
                            )
                        ) {
                            Text(if (isEditMode) "保存" else "添加", fontSize = 14.sp)
                        }
                    }
                }
            }
        }
    }
}

/**
 * 储蓄目标类型选择芯片
 */
@Composable
private fun SavingsGoalTypeChip(
    label: String,
    selected: Boolean,
    onSelected: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier
            .height(36.dp)
            .clickable(onClick = onSelected),
        color = if (selected) Color(0xFF6A11CB).copy(alpha = 0.7f) else Color.White.copy(alpha = 0.1f),
        shape = RoundedCornerShape(18.dp)
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = label,
                color = Color.White,
                fontSize = 13.sp,
                fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal
            )
        }
    }
}

/**
 * 图标选择项
 */
@Composable
private fun IconSelectionItem(
    iconName: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .size(36.dp)
            .clip(CircleShape)
            .background(
                if (isSelected) Color(0xFF6A11CB) 
                else Color.White.copy(alpha = 0.1f)
            )
            .border(
                width = if (isSelected) 1.dp else 0.dp,
                color = if (isSelected) Color.White else Color.Transparent,
                shape = CircleShape
            )
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        val icon = IconUtils.getIconByName(iconName)
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = Color.White,
            modifier = Modifier.size(18.dp)
        )
    }
} 